package com.wigball.java.jchef.model.ingredients;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.wigball.java.jchef.model.ingredients.impl.DryIngredient;
import com.wigball.java.jchef.model.ingredients.impl.LiquidIngredient;
import com.wigball.java.jchef.model.ingredients.impl.UnknownIngredient;
import com.wigball.java.jchef.parser.ParserException;

public abstract class IngredientFactory {

	private static final Pattern P = Pattern.compile("(?<initialValue>\\d*)\\s*((?<measureType>heaped|level)?\\s*(?<measure>g|kg|pinch(es)?|ml|l|dash(es)?|cup(s)?|teaspoon(s)?|tablespoon(s)?))?\\s*(?<ingredientName>.*)"); 
	
	public static final Ingredient fromString(String s) {
		Matcher m = P.matcher(s);
		
		if (!m.matches()) {
			throw new ParserException("\"" + s + "\" is not a well formed ingredient!");
		}
		
		String initialValue = m.group("initialValue");
		String measureType = m.group("measureType");
		String measure = m.group("measure");
		String ingredientName = m.group("ingredientName");
		
		AbstractIngredient result;
		
		if ("g".equals(measure) || "kg".equals(measure) || "pinch".equals(measure) || "pinches".equals(measure) || "heaped".equals(measureType) || "level".equals(measureType)) {
			result = new DryIngredient();
		}
		else if ("ml".equals(measure) || "l".equals(measure) || "dash".equals(measure) || "dashes".equals(measure)) {
			result = new LiquidIngredient();
		}
		else {
			result = new UnknownIngredient();
		}
		
		result.setName(ingredientName);
		result.setMeasureType(measureType);
		result.setMeasure(measure);
		
		if (initialValue != null) {
			try {
				result.setValue(Integer.parseInt(initialValue));
			}
			catch (Exception e) {
				throw new ParserException(e);
			}
		}
		
		return result;
	}
	
}
